package co.pushmall.mp.controller;

import cn.hutool.core.util.ObjectUtil;
import co.pushmall.mp.domain.PushMallWechatReply;
import co.pushmall.mp.service.PushMallWechatReplyService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author pushmall
 * @date 2019-10-10
 */
@Api(tags = "商城:微信回復管理")
@RestController
@RequestMapping("api")
public class WechatReplyController {

    private final PushMallWechatReplyService pushMallWechatReplyService;

    public WechatReplyController(PushMallWechatReplyService pushMallWechatReplyService) {
        this.pushMallWechatReplyService = pushMallWechatReplyService;
    }

    @ApiOperation(value = "查询")
    @GetMapping(value = "/PmWechatReply")
    @PreAuthorize("@el.check('admin','PushMallWECHATREPLY_ALL','PushMallWECHATREPLY_SELECT')")
    public ResponseEntity getPushMallWechatReplys() {
        return new ResponseEntity(pushMallWechatReplyService.isExist("subscribe"), HttpStatus.OK);
    }


    @ApiOperation(value = "新增自动回复")
    @PostMapping(value = "/PmWechatReply")
    @PreAuthorize("@el.check('admin','PushMallWECHATREPLY_ALL','PushMallWECHATREPLY_CREATE')")
    public ResponseEntity create(@RequestBody String jsonStr) {
        //if(StrUtil.isNotEmpty("22")) throw new BadRequestException("演示环境禁止操作");
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        PushMallWechatReply yxWechatReply = new PushMallWechatReply();
        PushMallWechatReply isExist = pushMallWechatReplyService.isExist(jsonObject.get("key").toString());
        yxWechatReply.setKey(jsonObject.get("key").toString());
        yxWechatReply.setStatus(Integer.valueOf(jsonObject.get("status").toString()));
        yxWechatReply.setData(jsonObject.get("data").toString());
        yxWechatReply.setType(jsonObject.get("type").toString());
        if (ObjectUtil.isNull(isExist)) {
            pushMallWechatReplyService.create(yxWechatReply);
        } else {
            yxWechatReply.setId(isExist.getId());
            pushMallWechatReplyService.update(yxWechatReply);
        }

        return new ResponseEntity(HttpStatus.CREATED);
    }


}
